package two_xia.ex2.three02;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.lang.reflect.Constructor;

public class UserFactory {

    public static User getUser(int permission) {

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            //这个路径是你的xml文件
            Document doc = db.parse("src/two_xia/ex2/three02/Employee.xml");
            //获取标签是employee的数据，包含role和id
            NodeList nodeList = doc.getElementsByTagName("employee");

            for (int i = 0; i < nodeList.getLength(); i++) {
                Element element = (Element) nodeList.item(i);
                String role = element.getAttribute("role");
                //从xml中获取的id数据原本是string类型，转化成int
                int id = Integer.parseInt(element.getAttribute("id"));
                if (id == permission) {
                    Class<?> cls = Class.forName(role);
                    Constructor<?> constructor = cls.getConstructor();
                    Object obj = constructor.newInstance();
                    return (User) obj;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
        
    }

}
